package com.cyl.manager.act.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.act.domain.entity.CouponActivity;
import com.cyl.manager.act.domain.entity.MemberCoupon;
import com.cyl.manager.act.mapper.CouponActivityMapper;
import com.cyl.manager.act.mapper.MemberCouponMapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.ruoyi.common.core.redis.RedisCache;

/**
 * 优惠券活动表Service业务层处理
 *
 * @author zcc
 */
@Service
public class CouponActivityNewService {
    @Autowired
    private CouponActivityMapper couponActivityMapper;
    @Autowired
    private MemberCouponMapper memberCouponMapper;
    
    @Autowired
    private MemberMapper memberMapper;
    
    @Autowired
    private RedisCache redisCache;
    
    
    public CouponActivity selectCheckById(Long id) {
    	String key = "COUPON_ACTIVITY_FLQLQ_"+id;
    	CouponActivity couponActivity = redisCache.getCacheObject(key);
    	if(couponActivity==null) {
    		couponActivity = couponActivityMapper.selectById(id);
    	    redisCache.setCacheObject(key, couponActivity, 5, TimeUnit.SECONDS);

    	}
    	return couponActivity;
    }

  
    
    
  
    public Boolean receiveCouponByFlq(Long id,Member member) {
        CouponActivity couponActivity = selectCheckById(id);
        if (couponActivity == null) {
           throw new RuntimeException("未找到活动");
        }
        if (couponActivity.getQlx().intValue() == 2) {
            throw new RuntimeException("券类型不正确");
         }
        //判断有没有余量
        if (couponActivity.getLeftCount() < 1) {
        	 throw new RuntimeException("活动已没有余额");
        }
        //活动未开始或者已经结束
        if(couponActivity.getPublishstatus().intValue() != 1) {
        	throw new RuntimeException("活动未开始或者已经结束");//活动未开始或者已经结束
        }
        //判断时间有没有超
        LocalDateTime now = LocalDateTime.now();
        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
        	 throw new RuntimeException("活动已过期");
        }
        //判断领的有没有超
//        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("member_id", memberId)
//                .eq("coupon_activity_id", id);
//        Integer count = memberCouponMapper.selectCount(queryWrapper);
//        if (count != null && count >= 1) {
//       	 	throw new RuntimeException("你已领取");
//        }
        //兑换券
      
        int saveCount = saveMemberCoupon(couponActivity, member,1,couponActivity.getQlx()+"","直播间领取");
        // (id);
        return saveCount > 0;
    }
    
 
     
    /**
     * 	时长券补发
     * @param id
     * @param memberId
     * @return
     */
    public int receiveCouponScqBf(Long id,Long memberId) {
        CouponActivity couponActivity = selectCheckById(id);
        if (couponActivity == null) {
        	return 0;
            //throw new RuntimeException("未找到活动");//中文不能变
        }
        //判断有没有余量
        if (couponActivity.getLeftCount() < 1) {
        	return 0;
            //throw new RuntimeException("活动已没有余额");//中文不能变
        }
        //判断时间有没有超
        LocalDateTime now = LocalDateTime.now();
        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
        	return 0;
            //throw new RuntimeException("活动已过期");//中文不能变
        }
        Member member =  memberMapper.selectById(memberId);
        if(member==null) {
        	return 0;
        }
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId)
                .eq("coupon_activity_id", id);
        Integer count = memberCouponMapper.selectCount(queryWrapper);
        if (count != null && count >= couponActivity.getUserLimit()) {
        	return 0;
        }
        return saveMemberCoupon(couponActivity, member,1,couponActivity.getQlx()+"","直播间系统补发");
    }
    
    
    
    
    public Map<String, Object> receiveCouponScq(Long id,Member member) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("zt", false);
    	Long memberId = member.getId();
    	
        CouponActivity couponActivity = selectCheckById(id);
        if (couponActivity == null) {
            throw new RuntimeException("未找到活动");//中文不能变
        }
        if (couponActivity.getQlx().intValue() == 1) {
            throw new RuntimeException("券类型不正确");//中文不能变
         }
        //判断有没有余量
        if (couponActivity.getLeftCount() < 1) {
            throw new RuntimeException("活动已没有余额");//中文不能变
        }
      //活动未开始或者已经结束
        if(couponActivity.getPublishstatus().intValue() != 1) {
        	throw new RuntimeException("活动未开始或者已经结束");//活动未开始或者已经结束
        }
        //判断时间有没有超
        LocalDateTime now = LocalDateTime.now();
        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
            throw new RuntimeException("活动已过期");//中文不能变
        }
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId)
                .eq("coupon_activity_id", id);
        Integer count = memberCouponMapper.selectCount(queryWrapper);
       
        
        boolean sfgxGgkkssj = false;//是否跟新开始时长
        Long zbjlid = couponActivity.getZbjlid();
        String memberKey = "ZBJ_GKSC_"+zbjlid+"_"+memberId;
        
        //时长券
    	Long gkkssj =  redisCache.getCacheObject(memberKey);
		int  dbgksc = couponActivity.getGksc();
    	if(gkkssj==null || gkkssj.longValue() == 0L) {
    		map.put("zt", false);
        	map.put("gksc", 0);
        	map.put("dbgksc", dbgksc);
        	map.put("msg", "观看时长只有"+0+"分钟！，不足"+dbgksc+"分钟！");
        	return map;
    	}
		long thisTime = System.currentTimeMillis();
		int gksc = (int) (((thisTime-gkkssj)/1000)/60);
		
    	if(dbgksc > gksc) {
        	map.put("zt", false);
        	map.put("gksc", gksc);
        	map.put("gkscTime", thisTime-gkkssj);
        	map.put("dbgksc", dbgksc);
        	map.put("msg", "观看时长只有"+gksc+"分钟！，不足"+dbgksc+"分钟！");
        	return map;
    	    // throw new RuntimeException("观看时长只有"+gksc+"分钟！，不足"+gksc+"分钟！");
    	}else {
    		sfgxGgkkssj = true;//是否跟新开始时长
    	}
   
    	
        if (count != null && count >= couponActivity.getUserLimit()) {
        	map.put("count", count);
        	return map;
        }
        
        int saveCount = saveMemberCoupon(couponActivity, member,1,couponActivity.getQlx()+"","直播间领取");
        // (id);
        if(sfgxGgkkssj) {
            redisCache.setCacheObject(memberKey, System.currentTimeMillis(),60*5,TimeUnit.MINUTES);
        }
        map.put("zt", saveCount > 0);
        if(saveCount > 0) {
        	map.put("count", count+1);
        }
        return map;
    }
 
    
    
    
    public int saveMemberCoupon(CouponActivity activity, Member member,Integer count,String lx,String bz) {
    	Long memberId = member.getId();
    	
        MemberCoupon memberCoupon = new MemberCoupon();
        memberCoupon.setCouponActivityId(activity.getId());
        memberCoupon.setTitle(activity.getTitle());
        memberCoupon.setUseScope(activity.getUseScope());
        memberCoupon.setProductIds(activity.getProductIds());
        memberCoupon.setCouponAmount(activity.getCouponAmount());
        memberCoupon.setMinAmount(activity.getMinAmount());
        memberCoupon.setUseIntegral(activity.getUseIntegral());
        memberCoupon.setCouponType(activity.getCouponType());
        memberCoupon.setBeginTime(LocalDateTime.now());
        memberCoupon.setEndTime(activity.getEndTime());
        memberCoupon.setCreateTime(LocalDateTime.now());
        memberCoupon.setMemberId(memberId);
        memberCoupon.setAmkey(memberId+"_"+activity.getId()+"_"+count);
        memberCoupon.setUseStatus(0);
        memberCoupon.setDeptZbjId(activity.getDeptZbjId());
        memberCoupon.setCouponCategoryId(activity.getCategoryid()); 
        memberCoupon.setLx(lx); //券类型 1福利券 2时长券
        memberCoupon.setBz(bz); //券类型 1福利券 2时长券
        
        memberCoupon.setDeptZbjId(member.getDeptZbjId());
        memberCoupon.setDeptTzId(member.getDeptTzId());
        memberCoupon.setDeptDpId(member.getDeptDpId());
        memberCoupon.setSpreaduid(member.getSpreaduid());
        return memberCouponMapper.insert(memberCoupon);
    }
 
    
 
    

}
